//
//  SYTradeView.m
//  SYKeyboard
//
//  Created by hc on 2019/3/22.
//  Copyright © 2019 hc. All rights reserved.
//

#import "SYTradeView.h"
#import "SYNumKeyboard.h"
#import "SYTradeInputView.h"

@interface SYTradeView () <SYBaseKeyboardDelegate, SYTradeInputViewDelegate>

@property (nonatomic, strong) SYTradeInputView *inputView;
@property (nonatomic, strong) SYNumKeyboard *numKeyboard;

@end

@implementation SYTradeView

- (instancetype)init {
    if (self = [super initWithFrame:CGRectMake(0, 0, SYKeyboardScreenWidth, SYKeyboardScreenHeight)]) {
        self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.4];
        
        [self setupSubviews];
        self.type = TradeSixType;
        self.titleStr = @"请输入支付密码";
    }
    return self;
}

- (void)setType:(TradeType)type {
    _type = type;
    
    self.inputView.maximum = type;
}

- (void)setTitleStr:(NSString *)titleStr {
    _titleStr = titleStr;
    
    self.inputView.titleStr = titleStr;
}

- (void)show {
    [self.inputView setNeedsDisplay];
    [[UIApplication sharedApplication].keyWindow addSubview:self];
}

- (void)dismiss {
    [self removeFromSuperview];
}

- (void)setupSubviews {
    NSInteger height = SYKeyboardHeight;
    if (SYKeyboardIS_iPhoneX) {
        height += 49;
    }
    
    self.numKeyboard = [[SYNumKeyboard alloc] initWithFrame:CGRectMake(0, SYKeyboardScreenHeight - height, SYKeyboardScreenWidth, height)];
    self.numKeyboard.delegate = self;
    self.numKeyboard.isNumKeyboard = YES;
    [self addSubview:self.numKeyboard];
    
    self.inputView = [[SYTradeInputView alloc] initWithFrame:CGRectMake(0, SYKeyboardScreenHeight - height - SYKeyboardScreenWidth*0.596026, SYKeyboardScreenWidth, SYKeyboardScreenWidth*0.596026)];
    self.inputView.delegate = self;
    [self addSubview:self.inputView];
}

#pragma mark - SYTradeInputViewDelegate
- (void)password:(NSString *)password {
    if (self.delegate && [self.delegate respondsToSelector:@selector(tradePassword:)]) {
        [self.delegate tradePassword:password];
    }
}
- (void)popAction {
    [self dismiss];
}

#pragma mark - SYBaseKeyboardDelegate
- (void)pressKey:(NSString *)key keyType:(SYKeyType)keyType keyboardType:(SYKeyboardType)keyboardType {
    if (keyType == DoneKeyType) {
    }else if (keyType == DeleteKeyType) {
        if (self.inputView.nums.count > 0) {
            [self.inputView.nums removeLastObject];
            [self.inputView setNeedsDisplay];
        }
    }else {
        if (self.inputView.nums.count < self.type) {
            [self.inputView.nums addObject:key];
            [self.inputView setNeedsDisplay];
        }
    }
}

@end
